package com.example.test.api.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.test.CourseDo;
import com.example.test.User;
import com.example.test.api.CourseRest;
import com.example.test.contract.CreateCourseParam;
import com.example.test.dao.CourseDao;
import com.example.test.dao.UserDao;
import com.example.test.suppert.base.result.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by lsl on 2021/3/5.
 */
@Service
@Slf4j
public class CourseRestImpl implements CourseRest {

    @Autowired
    private CourseDao courseDao;
    @Autowired
    private UserDao userDao;

    @Override
    public BaseResult<Boolean> create(@Valid CreateCourseParam param) {
        List<User> list = userDao.list(new QueryWrapper<>(User.builder().name(param.getUserName()).build()));
        if (CollectionUtils.isEmpty(list)) {
            return BaseResult.error("找不到用户");
        }
        Long userId = list.get(0).getId();
        CourseDo toInsert = CourseDo.builder()
                .userId(userId)
                .courseName(param.getCourseName())
                .score(param.getScore())
                .examDate(param.getExamDate())
                .build();
        courseDao.insert(toInsert);
        log.info("exam date: {}", param.getExamDate());
        return BaseResult.success(Boolean.TRUE);
    }
}
